<?php

namespace Jja;


class Utils{

    public static function  getPlatform( $platform ){
        switch ($platform){
            case 'android':
                return 1;
            case 'iOS':
                return 2;
        }
    }

    public static function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }

    public static function makeOutTradeNo(){
        return time().self::randCode(6 , 1);
    }

    public static function makeOrderSn(){
        return date('YmdHis') . self::randCode(4, 1);
    }

    /**
     * 生成随机字符串
     * @param $length int 要生成的随机字符串长度
     * @param $type 0，数字+大小写字母；1，数字；2，小写字母；3，大写字母；4，特殊字符；-1，数字+大小写字母+特殊字符
     * @return string
     */
    public static function randCode($length = 5, $type = 0) {
        $arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|");
        if ($type == 0) {
            array_pop($arr);
            $string = implode("", $arr);
        } elseif ($type == "-1") {
            $string = implode("", $arr);
        } else {
            $string = $arr[$type];
        }
        $count = strlen($string) - 1;
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            $code .= $string[rand(0, $count)];
        }
        return $code;
    }


    /**
     * 数组转对象
     * @param array $data
     * @param string $k_name
     * @param string $v_name
     * @return array
     */
    public static function arrayToObj( array $data , $k_name = 'key_id' , $v_name = 'value' ){
        $temp = [];
        foreach ( $data as $key => $value ){
            array_push( $temp , [
                $k_name => (string)$key,
                $v_name => $value
            ]);
        }
        return $temp;
    }


    /**
     * 商品价格显示格式化
     * @param $price
     * @param int $num
     * @return string
     */
    public static function formatItemPrice($price, $num = 2)
    {
        $str = sprintf("%." . $num . "f", $price);
//        return strval(floatval($str));
        return $str;
    }

    /**
     * @param $star
     * @return string
     */
    public static function getStarText( $star  = ''){

        $star = $star ?? 5;

        if( $star >= 4 ){
            $star_text = '非常好';
        }else if( $star >= 3 ){
            $star_text = '一般';
        }else if( $star >= 2 ){
            $star_text = '差';
        }else{
            $star_text = '极差';
        }
        return $star_text;
    }

    /**
     * 获取日期之间有多少月份
     * @param $s 开始时间 例如：2020-08-01
     * @param $e 结束时间 例如：2020-10-01
     * @throws \Exception
     */
    public static function getMonths($s,$e){
//        $s = '2020-08-01';
//        $e = '2021-08-01';

        $start    = new \DateTime($s.' 00:00:00');
        $end      = new \DateTime($e.' 23:59:59');
        // 时间间距 这里设置的是一个月
        $interval = \DateInterval::createFromDateString('1 month');
        $period   = new \DatePeriod($start, $interval, $end);

        $months=[];
        foreach ($period as $dt) {
            $months[]=$dt->format("Y-m");
        }
        return $months;
    }


    /**
     * 获取当前日期的前6个月
     * @param $s 开始时间 例如：2020-08-01
     * @param $e 结束时间 例如：2020-10-01
     * @throws \Exception
     */
    public static function getMonthsBeforeSix(){
        $months=[];
        for($i=0;$i<6;$i++){
            $d = date('Y-m',strtotime(" -$i month", strtotime(date('Y-m'))));
            $months[]=$d;
        }
        return $months;
    }

    /**
     * 简化时间显示
     * @param $time
     * @return string
     */
    public static function format_date($time){
        $t=time()-$time;
        $f=array(
            '31536000'=>'年',
            '2592000'=>'个月',
            '604800'=>'星期',
            '86400'=>'天',
            '3600'=>'小时',
            '60'=>'分钟',
            '1'=>'秒'
        );
        foreach ($f as $k=>$v)    {
            if (0 !=$c=floor($t/(int)$k)) {
                return $c.$v.'前';
            }
        }
    }

    /**
     * 分钟转时分 (例如：10:10)
     * @param $time  430分钟
     * @return string 07:10
     */
    public static function format_time_to_hour_min($time = 0){
        if(!$time){
            return '00:00';
        }
        $hours = floor($time / 60);
        if ($hours < 10) {
            $hours = '0' . $hours;
        }
        $minutes = ($time % 60);
        if ($minutes < 10) {
            $minutes = '0' . $minutes;
        }
        return $hours.':'.$minutes;
    }

    /**
     * 分钟转时分 (例如：10:10)
     * @param $time  430分钟
     * @return string 07:10
     */
    public static function format_time_to_hour_min_c($time = 0){
        if(!$time ||$time<0){
            return '00小时00分钟';
        }
        $hours = floor($time / 60);
        if ($hours < 10) {
            $hours = '0' . $hours;
        }
        $minutes = ($time % 60);
        if ($minutes < 10) {
            $minutes = '0' . $minutes;
        }
        return $hours.'小时'.$minutes.'分钟';
    }

    /**
     * 分钟转时分 (例如：7小时10)
     * @param $time  430分钟
     * @return string 例如：7小时10
     */
    public static function format_time_to_hour_and_min($time){
        $hours = floor($time / 60);
        $minutes = ($time % 60);
        if ($minutes < 10) {
            $minutes = '0' . $minutes;
        }

        if(empty($hours)){
            return $minutes;
        }
        return $hours.'小时'.$minutes;
    }

    /**
     * 00:00 转为int 型；
     * @param string $time
     * @return float|int
     */
    public static function format_time_to_int( string $time = '' ){

        // if(strpos( $time , ':'  ) === false)
        //     throw new Exception('参数格式错误，参数为时间格式，例如：00:00');

        if( !$time )
            $time = date('H:i');

        $result = explode( ':' , $time );

        $hours = intval( $result[0] );
        $total = 0;
        if( $hours ){
            $total += $hours * 60;
        }
        return $total + intval( $result[1] );
    }


    public static function getWeekFormat($time = '' , $format = 1){

        $time = $time ? $time : time();

        $week = date('w' , $time);

        $str = '';
        switch ($week){
            case 1:
                $str = '一';
                break;
            case 2:
                $str = '二';
                break;
            case 3:
                $str = '三';
                break;
            case 4:
                $str = '四';
                break;
            case 5:
                $str = '五';
                break;
            case 6:
                $str = '六';
                break;
            case 7:
                $str = '日';
                break;
        }
        return $format ? '星期'.$str : $str;
    }

    /**
     * @return false|int
     */
    public static function getToDayTime(){
        return strtotime(date('Y-m-d'));
    }

    /**
     * 返回一天的时间范围
     * @param string $day 传入的格式为 2020-05-26 为空返回今天的范围
     * @return array
     */
    public static function getTodayRange($day = ''){

        $day = $day ? $day : date('Y-m-d');

        $dayTime = strtotime($day);
        $endTime = strtotime( $day.' +1 day' )-1;
        return [ $dayTime , $endTime ];
    }


    public static function curl_request($url, $post = '', $cookie = '', $returnCookie = 0, $json = false) {

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        if (substr($url, 0, strlen("https://")) == "https://") {
            // https请求
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        // curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
        if ($post) {
            if ($json) { //发送JSON数据
                $post = json_encode($post);
                curl_setopt($curl, CURLOPT_HEADER, 0);
                curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                        'Content-Type: application/json; charset=utf-8',
                        'Content-Length:' . strlen($post)
                    )
                );
            } else {
                $post = http_build_query($post);
            }
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
        }
        if ($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return curl_error($curl);
        }
        curl_close($curl);
        if ($returnCookie) {
            list($header, $body) = explode("\r\n\r\n", $data, 2);
            preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
            if (isset($matches[1][0])) {
                $info['cookie'] = substr($matches[1][0], 1);
                $info['content'] = $body;
            } else {
                $info['cookie'] = $matches[1];
                $info['content'] = $body;
            }
            return $info;
        } else {
            return $data;
        }
    }


    /**
     * 手机隐藏个中间部分用 * 代替
     * @param $str
     * @return mixed
     */
    public static function yc_phone($str)
    {
        return substr_replace($str, '****', 3, 4);

    }

    // 获取某个时间戳是今天，还是明天，还是后天，超出的用日期
    public static function timeToFormat($time){
        $target = date('Y-m-d', $time);

        switch ($target) {
            case date('Y-m-d'):
                $str = '今天';
                break;
            case date('Y-m-d', strtotime('+1 days')):
                $str = '明天';
                break;
            case date('Y-m-d', strtotime('+2 days')):
                $str = '后天';
                break;
            default:
                $str = date('m-d', $time);
                break;
        }
        return $str.' '.date('H:i', $time);

    }
}